using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Windows.Forms;

namespace MyAnimeList
{
    public class LibDataProcess
    {
        public static string Login(string username, string password)
        {
            try
            {
                var url = ConfigurationManager.AppSettings["Verify"];
                if (string.IsNullOrEmpty(url))
                {
                    url = "https://myanimelist.net/api/account/verify_credentials.xml";
                    string message;
                    if (SaveConfig(new Dictionary<string, string>
                    {
                        {"Verify", url}
                    }, out message) == false)
                    {
                        return message;
                    }
                }

                var request = WebRequest.Create(url);
                {
                    request.ContentType = "xml";
                    request.Method = "GET";
                    request.Credentials = new NetworkCredential(username, password);

                    var res = request.GetResponse();

                    var stream = res.GetResponseStream();

                    if (stream != null)
                    {
                        //var str = new StreamReader(stream).ReadToEnd();

                        return null;
                    }

                    return "Failed to connect.";
                }
            }
            catch (Exception exception)
            {
                return exception.Message.Contains("401") ? "Username or password is wrong." : exception.Message;
            }
        }

        public static bool SaveConfig(Dictionary<string, string> data, out string errorMessage)
        {
            try
            {
                foreach (var pair in data)
                {
                    var key = pair.Key;
                    var value = pair.Value;
                    var config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
                    config.AppSettings.Settings.Add(new KeyValueConfigurationElement(key, value));
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }

                errorMessage = null;
                return true;
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return false;
            }
        }
    }
}